# PROJECT: WhatsApp Order & Route-Based Delivery Automation System

Act as a **Senior Full-Stack Developer, WhatsApp Automation Engineer, System Architect, and AI Workflow Expert**.

I need you to DESIGN AND BUILD a complete, production-ready **WhatsApp Order Management + Automatic Delivery Scheduling System** for a local distribution business.

Do not only explain the concept. Create the complete architecture, database structure, automation logic, dashboard flow, APIs/webhooks, and implementation plan. Wherever possible, generate working code.

---

# 1. BUSINESS MODEL

The business supplies products to retailers/shops using its **own delivery vehicles**.

Current situation:

- Business operates **6 days per week**.
- Different areas/routes are assigned to different days.
- The same 6-day delivery cycle repeats every week.
- Business currently has approximately **1,000 existing customers**.
- New customers are continuously being added.
- Orders currently come mainly through WhatsApp.
- There may be **multiple WhatsApp numbers** receiving orders.
- Orders are currently written manually in a diary.
- Staff manually identifies the customer's area.
- Staff manually checks which day the vehicle goes to that area.
- Staff manually separates Monday, Tuesday, Wednesday, etc. orders.
- This process is time-consuming and needs automation.

The business currently has its own delivery vehicles.

Online payment gateway integration is NOT required in the first version.

---

# 2. MAIN OBJECTIVE

Build a system where:

CUSTOMER WHATSAPP MESSAGE
↓
AI / AUTOMATION READS MESSAGE
↓
IDENTIFIES WHETHER CUSTOMER WANTS TO PLACE AN ORDER
↓
EXTRACTS ORDER INFORMATION
↓
IDENTIFIES CUSTOMER AREA
↓
MATCHES AREA WITH DELIVERY ROUTE
↓
CALCULATES NEXT DELIVERY DATE
↓
CREATES ORDER
↓
SENDS AUTOMATIC WHATSAPP CONFIRMATION
↓
ADDS ORDER TO ADMIN DASHBOARD
↓
GROUPS ORDERS BY DELIVERY DAY / ROUTE
↓
ADMIN CAN VIEW DAILY DELIVERY LIST

The system should minimize manual work as much as possible.

---

# 3. WHATSAPP ORDER FLOW

Example customer message:

"Sir 5 box floor cleaner aur 10 handwash bhej dena."

OR:

"Kal wala same order bhej dena."

OR:

"2 carton tissue chahiye."

OR:

"Order book kar do."

The system should understand that the customer is trying to place an order.

If required information is missing, the chatbot should ask follow-up questions.

Example:

Customer:
"5 box cleaner bhej do."

Bot:
"Sure. Please confirm your delivery area/location."

Customer:
"Zirakpur"

The system should then check the delivery schedule.

---

# 4. CUSTOMER DATABASE

Maintain a customer database containing fields such as:

Customer ID
Customer Name
Business / Shop Name
WhatsApp Number
Alternate Number
Area
City
Route
Delivery Day
Address
Landmark
Previous Orders
Last Order Date
Customer Status
Notes

If an existing customer sends a WhatsApp message, identify them automatically using their phone number.

If their area/address is already saved, DO NOT repeatedly ask for it.

---

# 5. AREA → ROUTE → DAY MAPPING

Admin must be able to configure delivery routes.

Example only:

Monday Route:
Chandigarh → Zirakpur → Dera Bassi → Lalru → Ambala

Tuesday Route:
Area A → Area B → Area C

Wednesday Route:
Area D → Area E → Area F

etc.

IMPORTANT:

Do NOT hard-code these locations.

Create an Admin Route Management section where the business owner can:

Add Area
Edit Area
Delete Area
Assign Area to Route
Assign Route to Delivery Day
Change Delivery Day
Add small/local areas
Add route stops
Reorder route stops
Temporarily disable a route

The system must support hundreds of small local areas.

For example, a route may contain:

Chandigarh
Zirakpur
Dera Bassi
Lalru
Ambala

plus smaller locations between them.

---

# 6. DELIVERY DATE CALCULATION

When an order is confirmed:

1. Detect customer's area.
2. Find its assigned delivery day.
3. Calculate the NEXT upcoming occurrence of that delivery day.
4. Save that date as the expected delivery date.

Example:

Customer Area = Zirakpur
Assigned Route = Monday
Today = Thursday

Expected Delivery = Next Monday.

If today's route has already departed or the daily order cutoff time has passed, schedule it for the NEXT week's route.

Admin should be able to configure cutoff time.

Example:

Monday Route Cutoff = Sunday 8:00 PM

After cutoff, new orders should automatically move to the next Monday unless admin manually overrides them.

---

# 7. AUTOMATIC WHATSAPP CONFIRMATION

After successfully booking an order, send something like:

"Hi {{customer_name}},

Your order has been confirmed. ✅

Order ID: {{order_id}}
Delivery Area: {{area}}
Expected Delivery: {{delivery_day}}, {{delivery_date}}

Our delivery vehicle is scheduled to visit your area on this day.

Thank you."

Message templates must be editable from Admin Dashboard.

---

# 8. ORDER MANAGEMENT

Every order should contain:

Order ID
Customer
Phone Number
Products
Quantities
Order Notes
Order Source
Area
Route
Delivery Day
Delivery Date
Order Created Time
Status
Payment Status
Delivery Status
Assigned Vehicle
Assigned Driver

Possible statuses:

New
Needs Confirmation
Confirmed
Scheduled
Out for Delivery
Delivered
Cancelled
Rescheduled

---

# 9. ADMIN DASHBOARD

Build a professional web dashboard.

Main dashboard should show:

Today's Orders
Tomorrow's Orders
Monday Orders
Tuesday Orders
Wednesday Orders
Thursday Orders
Friday Orders
Saturday Orders

Also show:

Total Orders
Confirmed Orders
Pending Orders
Delivered Orders
Cancelled Orders
Customers
Routes
Vehicles

Example:

MONDAY
Total Orders: 37

TUESDAY
Total Orders: 24

WEDNESDAY
Total Orders: 41

Admin should be able to click any day and see the complete delivery list.

---

# 10. DAILY DELIVERY SHEET

Generate a route-wise delivery sheet containing:

Sequence Number
Customer Name
Shop Name
Phone
Area
Full Address
Products
Quantity
Order ID
Payment Status
Delivery Status
Notes

Allow:

Print
PDF Export
Excel/CSV Export

Also create a mobile-friendly driver view.

---

# 11. DRIVER / VEHICLE MANAGEMENT

Business currently uses its own vehicles, but the system should support multiple vehicles.

Create:

Vehicle Name
Vehicle Number
Driver Name
Driver Phone
Assigned Route
Assigned Orders

Admin should be able to assign a vehicle/driver to a day's route.

Driver should be able to view:

Today's Route
Customers
Phone Number
Address
Order
Delivery Status

Driver can mark:

Delivered
Customer Not Available
Cancelled
Payment Pending
Reschedule

---

# 12. AI MESSAGE UNDERSTANDING

Use AI/NLP only where useful.

The AI should classify incoming WhatsApp messages into categories such as:

NEW_ORDER
ORDER_UPDATE
ORDER_CANCEL
PRICE_QUERY
PRODUCT_QUERY
DELIVERY_QUERY
PAYMENT_QUERY
GENERAL_QUERY
UNKNOWN

For orders, extract structured information such as:

{
  "intent": "NEW_ORDER",
  "customer_name": "",
  "products": [
    {
      "product": "Floor Cleaner",
      "quantity": 5,
      "unit": "box"
    }
  ],
  "area": "Zirakpur",
  "confidence": 0.95
}

IMPORTANT:

AI must NOT automatically create an order when confidence is low.

Low-confidence messages should go into:

"Needs Human Review"

Admin can confirm/edit them manually.

---

# 13. HINGLISH SUPPORT

Customers may message in:

Hindi
English
Hinglish
Roman Hindi
Punjabi mixed with Hindi/English

Examples:

"Sir kal 5 box bhej dena"

"mera same wala order laga do"

"10 pcs cleaner aur 2 carton tissue chahiye"

"bhai monday wali gadi me maal bhej dena"

The system should understand common conversational messages.

---

# 14. REPEAT ORDERS

This is very important.

Customers may say:

"Same order bhej do."

"Last wala repeat kar do."

"Pichli baar wala maal bhejna."

System should fetch the customer's latest completed/confirmed order and show:

"Your previous order was:

5 × Floor Cleaner
10 × Handwash

Would you like to repeat this order?"

Only after confirmation should the new order be created.

---

# 15. WHATSAPP INTEGRATION

Use an official and scalable WhatsApp solution.

Preferred architecture:

WhatsApp Business Platform / WhatsApp Cloud API
+
Webhook
+
Backend
+
Database
+
Automation Engine
+
Admin Dashboard

Do not use unsafe WhatsApp Web scraping or unofficial automation if an official API can be used.

Explain exactly:

How incoming messages reach webhook
How messages are stored
How customer is identified
How AI processes message
How route is detected
How delivery date is calculated
How order is created
How confirmation is sent back through WhatsApp

---

# 16. MULTIPLE WHATSAPP NUMBERS

Architecture should be ready for more than one business WhatsApp number.

All orders should eventually appear in ONE centralized dashboard.

Store which WhatsApp number received each order.

---

# 17. HUMAN TAKEOVER

Admin/staff must be able to take over any WhatsApp conversation.

AI automation should stop responding when:

Human Takeover = ON

Admin should be able to reply manually.

Automation can be resumed later.

---

# 18. CUSTOMER ORDER HISTORY

When admin opens a customer profile, show:

Customer Details
Area
Route
Delivery Day
Total Orders
Previous Orders
Frequently Ordered Products
Last Order
Last Delivery
Cancelled Orders
Notes

---

# 19. PRODUCT MANAGEMENT

Create Product Master.

Fields:

Product ID
Product Name
Category
SKU
Unit
Price
Active/Inactive

AI should try to match informal product names to products in Product Master.

Example:

Customer says:
"blue cleaner"

Database product:
"Premium Blue Floor Cleaner 5L"

System can suggest the closest matching product but should ask for confirmation when ambiguous.

---

# 20. AUTOMATIC DAILY SUMMARY

Business owner should receive an automatic summary.

Example:

"Tomorrow's Delivery Summary

Route: Chandigarh → Ambala

Total Orders: 42
Total Customers: 38
Vehicle: Bolero 1

Zirakpur: 12 Orders
Dera Bassi: 10 Orders
Lalru: 8 Orders
Ambala: 12 Orders"

Also create dashboard notification.

---

# 21. DUPLICATE ORDER PROTECTION

Prevent accidental duplicate orders.

If the same customer sends the same order multiple times within a configurable period, flag:

"Possible Duplicate Order"

Do not silently create multiple orders.

---

# 22. ADMIN MANUAL CONTROL

Automation must NEVER lock the business owner into automatic decisions.

Admin should always be able to:

Edit Order
Delete/Cancel Order
Change Area
Change Route
Change Delivery Date
Change Customer
Change Products
Change Quantity
Assign Vehicle
Assign Driver
Reschedule Delivery
Manually Create Order
Manually Confirm Order

---

# 23. FAILURE / EDGE CASES

Design handling for:

Unknown Area
Incorrect Area Spelling
New Customer
Unknown Product
Ambiguous Product
No Quantity Mentioned
Multiple Products
Customer Changes Order
Customer Cancels Order
Customer Sends Voice Note
Customer Sends Image
Customer Sends Location
Customer Sends Address
Duplicate Message
WhatsApp webhook retry
AI failure
Database failure
WhatsApp API failure
Route temporarily unavailable
Vehicle unavailable
Holiday
Delivery rescheduling

Never lose an incoming order because AI or another service failed.

Raw incoming WhatsApp messages must be stored before processing.

---

# 24. AUDIT LOG

Maintain logs showing:

Message Received
AI Classification
Order Created
Order Edited
Route Assigned
Delivery Date Changed
WhatsApp Confirmation Sent
Admin Manual Changes
Order Delivered
Order Cancelled

Store timestamp and user/system responsible for each action.

---

# 25. SECURITY

Implement:

Admin Authentication
Role-Based Access
Secure API
Environment Variables
Webhook Verification
Rate Limiting
Input Validation
Database Backups
Error Logging
Audit Logs

Never expose WhatsApp API tokens or AI API keys in frontend code.

---

# 26. RECOMMENDED TECH STACK

Choose the best modern production-ready stack.

A possible stack is:

Frontend:
Next.js / React

Backend:
Node.js / Next.js API / NestJS

Database:
PostgreSQL

ORM:
Prisma

WhatsApp:
Official WhatsApp Cloud API

AI:
LLM API with structured JSON output

Queue:
Redis + BullMQ or equivalent

Deployment:
Vercel + Railway/Render/AWS or another suitable production architecture

You may improve this stack if you have a better recommendation.

Explain why you selected each component.

---

# 27. DATABASE DESIGN

Create proper relational database schema for at least:

Users
Customers
WhatsAppNumbers
Conversations
Messages
Products
Orders
OrderItems
Areas
Routes
RouteStops
DeliverySchedules
Vehicles
Drivers
Deliveries
MessageTemplates
Notifications
AuditLogs

Define relationships, indexes and important constraints.

---

# 28. CORE AUTOMATION LOGIC

Implement logic similar to:

Incoming WhatsApp Message
→ Save Raw Message
→ Identify WhatsApp Business Number
→ Identify Customer
→ Retrieve Conversation Context
→ AI Intent Classification
→ Extract Products / Quantity / Area
→ Validate Product
→ Validate Area
→ Retrieve Customer Saved Address
→ Determine Route
→ Determine Next Delivery Day
→ Apply Cutoff Rules
→ Detect Duplicate
→ Ask for Missing Information if required
→ Customer Confirmation
→ Create Order
→ Assign Route
→ Calculate Delivery Date
→ Send WhatsApp Confirmation
→ Add Order to Dashboard
→ Include Order in Daily Route Sheet
→ Log Every Action

---

# 29. IMPORTANT BUSINESS RULE

The most important relationship in the entire system is:

CUSTOMER AREA
→ ROUTE
→ DELIVERY DAY
→ NEXT DELIVERY DATE
→ ORDER
→ VEHICLE
→ DELIVERY

Design the database and backend around this relationship.

---

# 30. FUTURE SCALABILITY

The business may later use the same software for another business/product line, including premium mineral water distribution.

Therefore architecture should eventually support:

Multiple Businesses
Multiple Branches
Multiple WhatsApp Numbers
Thousands of Customers
Multiple Product Categories
Multiple Vehicles
Multiple Routes
Different Weekly Schedules

Do not overcomplicate Version 1, but do not design the database in a way that blocks future expansion.

---

# 31. UI REQUIREMENT

Dashboard must be:

Professional
Clean
Fast
Mobile Responsive
Simple enough for non-technical staff

Suggested navigation:

Dashboard
Orders
WhatsApp Inbox
Customers
Products
Delivery Schedule
Routes & Areas
Vehicles
Drivers
Reports
Message Templates
Automation
Settings

Use cards, tables, filters, search, status badges and clear actions.

---

# 32. BUILD ORDER

Do NOT try to create everything blindly at once.

Build in phases:

PHASE 1:
Architecture + Database + Route/Area system

PHASE 2:
Customer + Product + Order Management

PHASE 3:
WhatsApp webhook integration

PHASE 4:
AI intent/order extraction

PHASE 5:
Automatic route/day/date calculation

PHASE 6:
WhatsApp confirmation workflow

PHASE 7:
Dashboard + Daily delivery sheets

PHASE 8:
Driver workflow + Reports

PHASE 9:
Testing + Security + Deployment

---

# 33. WHAT I NEED FROM YOU

Start by giving me:

1. Complete system architecture
2. Recommended tech stack
3. Database schema
4. WhatsApp Cloud API architecture
5. Incoming webhook flow
6. AI message-processing architecture
7. Route/day scheduling algorithm
8. Order confirmation logic
9. Admin dashboard architecture
10. Folder/file structure

Then start generating the actual project.

For every file provide:

FILE PATH:
`/example/path/file.ts`

Then provide COMPLETE code.

Do not provide pseudo-code when real code can be written.

After each phase tell me:

- What has been completed
- What environment variables are required
- What external setup I need to perform
- How to run/test it
- What the next phase will build

Do not remove previously implemented functionality when moving to the next phase.

---

# FINAL GOAL

The final system should allow a retailer to simply send a WhatsApp message such as:

"Sir 5 box cleaner aur 10 handwash bhej dena."

And the system should eventually be capable of automatically determining:

WHO ordered
WHAT they ordered
WHERE they are located
WHICH route covers them
WHICH day the vehicle visits
WHAT the next delivery date is

Then:

Create the order
Send confirmation to customer
Add order to the correct delivery route
Show it in the admin dashboard
Include it in the driver's delivery list

with minimum manual intervention.

Start with the architecture and database design first, then proceed to implementation.